package com.tbvtc.agriculturalcreditchainserver2025.utils;

//import com.example.trace.exception.BaseException;
import com.tbvtc.agriculturalcreditchainserver2025.exception.FoodException;
import lombok.RequiredArgsConstructor;
import org.fisco.bcos.sdk.transaction.model.dto.TransactionResponse;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

@Component
@RequiredArgsConstructor // 自动注入
public class BlockBaseUtils { // 区块链操作工具类
//
    private final ResourceLoader resourceLoader;

    public String getPemFilePath(UserType userType) throws IOException {

        if (userType == UserType.ADMIN) {
            org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:pemFile/admin.pem");
            return resource.getFile().getAbsolutePath();
        } else if (userType == UserType.FARMER) {
            org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:pemFile/Farmer.pem");
            return resource.getFile().getAbsolutePath();
        } else if (userType == UserType.CONSUMER) {
            org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:pemFile/Consumer.pem");
            return resource.getFile().getAbsolutePath();
        } else if (userType == UserType.LOGISTIC) {
            org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:pemFile/Logistic.pem");
            return resource.getFile().getAbsolutePath();
        }
        return null;
    }


    public void checkIsSuccess(TransactionResponse transactionResponse, String errorMessage) { // 检查是否成功
        if (!Objects.equals(transactionResponse.getReceiptMessages(), "Success")) { // 若失败，抛出异常
//            throw new BaseException(errorMessage);
            throw new FoodException(500,"区块链出现错误"+errorMessage); // 这里抛出异常，需要处理
        }
    }
}
